package cn.rkylin.oms.common.event.message.handler;

import cn.rkylin.oms.common.event.message.*;
import cn.rkylin.oms.common.event.EventHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.scheduling.annotation.Async;

import java.util.Date;

public abstract class MessageHandler extends EventHandler<MessageEvent> {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void onEvent(MessageEvent event) throws Exception {
        MessageDefinition definition = event.getDefinition();
        if (definition.isEnabled() && !definition.isDeleted() && definition.getSendWay() == serveSendWay()) {
            internalHandle(event);
        }
    }

    final void writeLog(Date creationTime, Date sendTime, String content, SendResult result) {
        MessageLog log = new MessageLog();
        log.setCreationTime(creationTime);
        log.setSendTime(sendTime);
        log.setContent(content);
        log.setSendResult(result);
        mongoTemplate.insert(log);
    }

    protected abstract void internalHandle(MessageEvent event);

    protected abstract SendWay serveSendWay();
}
